import { Component, ComponentRef, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { PageLayoutCommonComponent } from '../page-layout-common.component';
import { Page } from 'src/app/models';
import { TemplateLayoutComponent } from 'src/app/common/zepride-template/template-layout/template-layout.component';
import { Subscription } from 'rxjs';
import { EngineService } from 'src/app/common/engines/services/engine.service';

@Component({
  selector: 'zepride-one-column',
  templateUrl: './one-column.component.html',
  styleUrls: ['./one-column.component.less']
})
export class OneColumnComponent implements OnInit, PageLayoutCommonComponent, OnDestroy {

  renderTemplate: (templateId: string, dom: HTMLElement, config?: any) => ComponentRef<TemplateLayoutComponent>;
  _page: Page;
  @ViewChild('containerRef') containerRef: ElementRef<HTMLDivElement>;
  componentRefs: ComponentRef<TemplateLayoutComponent>[];
  isUnAuthorized = false;
  templateAuth$: Subscription;
  /**
   * 模板权限的检测进度数据
   */
  authProgressData: {
    /**
     * 模板在页面中的id
     */
    templateItemId: string;
    /**
     * 是否不具备权限
     */
    isUnAuthorized: boolean;
    /**
     * 是否已经检测权限
     */
    isChecked: boolean;
  }[] = [];

  set page(data: Page) {
    if (!data.pageTmpItems || !data.pageTmpItems.length) {
      return;
    }
    this._page = data;
    const templateInfo: { templateId: string; index: number }[] = data.pageTmpItems.map(item => {
      return {
        templateId: item.templateId,
        index: item.index ? item.index : 0
      };
    });
    templateInfo.sort((prev, next) => {
      return prev.index - next.index;
    });
    const container = this.containerRef.nativeElement;
    this.componentRefs = [];
    templateInfo.forEach(info => {
      const wrapper = document.createElement('div');
      wrapper.style.position = 'relative';
      container.appendChild(wrapper);
      const ref = this.renderTemplate(info.templateId, wrapper, { showBtns: false });
      if (ref) {
        this.componentRefs.push(ref);
      }
    });
    this.authProgressData = this.buildAuthProgressData(this.componentRefs);
  }

  get page() {
    return this._page;
  }

  constructor(
    private engineService: EngineService
  ) { }

  ngOnInit(): void {
    this.onTemplateAuth();
  }

  buildAuthProgressData(refs: ComponentRef<TemplateLayoutComponent>[]) {
    const result = [];
    for (const ref of refs) {
      const item = {
        templateItemId: ref.instance.pageTmpItem.id,
        isUnAuthorized: false,
        isChecked: false
      };
      result.push(item);
    }
    return result;
  }

  onTemplateAuth() {
    this.templateAuth$ = this.engineService.templateAuthChange$.subscribe(data => {
      const templateItenId = data.templateItemId;
      const isUnAuthorized = data.isUnAuthorized;
      const item = this.authProgressData.find(authData => authData.templateItemId === templateItenId);
      if (item) {
        item.isChecked = true;
        item.isUnAuthorized = isUnAuthorized;
        this.setIsUnAuthorized();
      }
    });
  }
  /**
   * 判断页面是否不具备权限
   */
  setIsUnAuthorized() {
    this.isUnAuthorized = this.authProgressData.every(data => data.isChecked && data.isUnAuthorized);
  }

  ngOnDestroy() {
    if (Array.isArray(this.componentRefs) && this.componentRefs.length) {
      this.componentRefs.forEach(ref => {
        if (ref) {
          ref.destroy();
        }
      });
    }
    if (this.templateAuth$) {
      this.templateAuth$.unsubscribe();
    }
  }
}
